package com.bindservice;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.servicedemo.IRemoteBinder;

public class IPCServiceActivity extends AppCompatActivity implements View.OnClickListener, ServiceConnection {

    private Button btnBinder;
    private Button btnUnBinder;
    private EditText editData;
    private Button btnAsyData;
    private Intent intent;
    private IRemoteBinder remoteBinder;//根据aidl生成
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ipcservice);
        initView();
        intent=new Intent();//显式意图
        intent.setComponent(new ComponentName("com.servicedemo", "com.servicedemo.MyService"));
    }
    private void initView() {
        btnBinder = (Button) findViewById(R.id.btnBinder);
        btnUnBinder = (Button) findViewById(R.id.btnUnBinder);
        editData = (EditText) findViewById(R.id.editData);
        btnAsyData = (Button) findViewById(R.id.btnAsyData);

        btnBinder.setOnClickListener(this);
        btnUnBinder.setOnClickListener(this);
        btnAsyData.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnBinder:
                bindService(intent, this, BIND_AUTO_CREATE);
                break;
            case R.id.btnUnBinder:
                unbindService(this);
                remoteBinder=null;
                break;
            case R.id.btnAsyData: //传递数据
                if (remoteBinder != null) {
                    try {
                        remoteBinder.setData(this.editData.getText().toString());
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }
    //ServiceConnection 接口方法实现
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        //不能强制类型转换，不在同一个进程中
        remoteBinder = IRemoteBinder.Stub.asInterface(service);
    }
    @Override
    public void onServiceDisconnected(ComponentName name) {

    }
}
